require "Common/define"
require "Logic/Config"
require "Common/functions"

RedDotsSevenChallengeHandler = {};
local this = RedDotsSevenChallengeHandler;

function RedDotsSevenChallengeHandler.init()
    CloseEvent(Config.EventType.Fresh_TaskInfo, this.update);
    CloseEvent(Config.EventType.Res_TaskInfo_Get, this.update);

    ListenEvent(Config.EventType.Fresh_TaskInfo, this.update);
    ListenEvent(Config.EventType.Res_TaskInfo_Get, this.update);

    this.challengeIds = G.dataTable["t_newcomerchallenge"];

    return this;
end

--参数1：指定页签Id，nil代表检查所有页签
---七天挑战页签红点
function RedDotsSevenChallengeHandler.getFlag(...)
    local flag = Config.RedDotsFlagState.None;
    local tabId = ...;
    local tabList = {};
    --local startTime = logicMgr.CronMgr.GetNextDateTime(G.dataTable["t_global"][tostring(34)].f_string_value, math.floor(logicMgr.HeroManager.GetRoleInfo().createTime) - 24*60*60  + 3);
    --if startTime == "" then
    --    startTime = 0;
    --else
    --    startTime = tonumber(startTime);
    --end
    --local surpTime = HelperFunc.GetSurpTime(logicMgr.HeroManager.GetRoleInfo().createTime,7);
    --local surpDay = math.floor(surpTime / 24 / 3600);
    --surpDay = 7 - surpDay;
    local serverData = logicMgr.ActiveManager.getActiveServerDataList(10002);
    if serverData == nil then
        return flag;
    end
    local surpDay = logicMgr.ActiveManager.getActiveBeginDay(serverData.startTime);
    if tabId ~= nil then
        table.insert(tabList, tabId);
    else
        for k, v in pairs(this.challengeIds) do
            if v.f_ActivityId == 2001 then
                table.insert(tabList, v.f_Id);
            end
        end
    end
    for i = 1, #tabList do
        local config = this.challengeIds[tostring(tabList[i])];
        if config ~= nil and surpDay >= tabList[i] then
            flag = this.getFlagById(decodeJsonStrToTabel(config.f_TaskId));
            if flag == Config.RedDotsFlagState.Needful then
                break ;
            end
        end
    end
    if flag ~= Config.RedDotsFlagState.Needful and tabId == nil then
        local taskbox= G.dataTable["t_taskbox"];
        for k, v in pairs(taskbox) do
            if v.f_BoxType == 6 then
                local thisboxinfo = logicMgr.TaskManager.getTaskLivenessBoxServerData(v.f_BoxID);
                if thisboxinfo["reward"] == 1 then
                    flag = Config.RedDotsFlagState.Needful;
                    break;
                end
            end
        end
    end
    return flag;
end

function RedDotsSevenChallengeHandler.getFlagById(IdList)
    local flag = Config.RedDotsFlagState.None;
    for k, v in pairs(IdList) do
        local sevenDay = logicMgr.TaskManager.getTaskServerData(v);
        if sevenDay.status == 1 then
            flag = Config.RedDotsFlagState.Needful;
            break;
        end
    end
    return flag;
end

function RedDotsSevenChallengeHandler.update()
    RedDotsManager.addBroadcast(Config.RedDotsType.SevenChallenge);
end